package com.pmt.feedplayer.controller

import com.pmt.feedplayer.core.PlayerManager
import com.pmt.feedplayer.data.PlaybackState
import com.pmt.feedplayer.data.PlaybackProgress
import com.pmt.feedplayer.data.VideoItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * 播放器控制器
 * 管理播放状态和业务逻辑，连接 UI 层和核心播放层
 */
class PlayerController(
    private val playerManager: PlayerManager = PlayerManager.getInstance(),
    private val scope: CoroutineScope
) {
    // 状态管理
    private val _currentVideo = MutableStateFlow<VideoItem?>(null)
    private val _isAutoPlayEnabled = MutableStateFlow(true)
    private val _isMuted = MutableStateFlow(false)
    private val _showControls = MutableStateFlow(true)
    
    // 对外暴露的只读状态
    val currentVideo = _currentVideo.asStateFlow()
    val playbackStateFlow = playerManager.playbackStateFlow ?: MutableStateFlow(PlaybackState.IDLE)
    val progressFlow = playerManager.progressFlow ?: MutableStateFlow(PlaybackProgress(0, 0, 0))
    val isAutoPlayEnabled = _isAutoPlayEnabled.asStateFlow()
    val isMuted = _isMuted.asStateFlow()
    val showControls = _showControls.asStateFlow()
    val errors = playerManager.errorFlow ?: MutableSharedFlow<String>()
    
    init {
        // 监听错误流
        scope.launch {
            errors.collect { errorMessage ->
                // 处理播放器错误
                handlePlayerError(errorMessage)
            }
        }
        
        // 监听播放状态变化
        scope.launch {
            playbackStateFlow.collect { state ->
                handlePlaybackStateChange(state)
            }
        }
    }
    
    /**
     * 加载视频并准备播放
     */
    fun loadAndPlayVideo(videoItem: VideoItem) {
        _currentVideo.value = videoItem
        playerManager.loadVideo(videoItem.videoUrl)
        
        if (_isAutoPlayEnabled.value) {
            playerManager.play()
        }
    }
    
    /**
     * 切换播放/暂停状态
     */
    fun togglePlayPause() {
        // 由于无法直接访问Flow的最新值（需要在协程中），我们使用默认的暂停状态处理
        // 在实际应用中，应该在UI层通过collectAsState获取最新状态并传递给控制器
        playerManager.play() // 简化处理，直接尝试播放
    }
    
    /**
     * 开始播放
     */
    fun play() {
        playerManager.play()
    }
    
    /**
     * 暂停播放
     */
    fun pause() {
        playerManager.pause()
    }
    
    /**
     * 获取PlayerManager实例（用于平台特定实现）
     */
    fun getPlayerManager(): PlayerManager {
        return playerManager
    }
    
    /**
     * 跳转到指定进度
     */
    fun seekTo(position: Long) {
        playerManager.seekTo(position)
    }
    
    /**
     * 切换静音状态
     */
    fun toggleMute() {
        _isMuted.value = !_isMuted.value
        playerManager.setVolume(if (_isMuted.value) 0f else 1f)
    }
    
    /**
     * 切换自动播放
     */
    fun toggleAutoPlay() {
        _isAutoPlayEnabled.value = !_isAutoPlayEnabled.value
    }
    
    /**
     * 切换控制条显示
     */
    fun toggleControls() {
        _showControls.value = !_showControls.value
    }
    
    /**
     * 处理播放器错误
     */
    private fun handlePlayerError(errorMessage: String) {
        // 错误处理逻辑
        println("Player error: $errorMessage")
    }
    
    /**
     * 处理播放状态变化
     */
    private fun handlePlaybackStateChange(state: PlaybackState) {
        // 可以根据状态变化执行不同的业务逻辑
        when (state) {
            PlaybackState.ENDED -> {
                // 播放结束逻辑，如循环播放
                if (_isAutoPlayEnabled.value) {
                    playerManager.seekTo(0)
                    playerManager.play()
                }
            }
            PlaybackState.ERROR -> {
                // 错误处理逻辑已在 errorFlow 中处理
            }
            else -> Unit
        }
    }
}